import { currencyPrecisionCal, messages, queryCurrencyPrecision } from "share/common";
import React from 'react'
import { connect } from 'react-redux'
import { Form, Input ,Button, message, Row, Col, DatePicker, InputNumber, Select, Table, Affix, Modal, Spin, Popover } from 'antd'
const Option = Select.Option;
const FormItem = Form.Item;
const { TextArea } = Input;
import mileageExpenseService from 'containers/mileage-subsidy-expense/mileage-subsidy-expense.service'
import moment from 'moment'
import menuRoute from 'routes/menuRoute'
import 'styles/mileage-subsidy-expense/new-mileage-cost.scss'
import common  from'containers/financial-management/check-center/check-common'
import Condition from 'components/condition';
import ResizeTable from 'components/resize-table';
const { If } = Condition;

class NewMileageCost extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      record: null,
      tableLoading: false,
      pageLoading: false,
      date: '',
      type: 'new',
      currencyList: [],
      isInvoice: 0, //生成费用标识
      data: [],
      totalSubsidy: 0,
      totalMileage: 0,
      referenceMileage: 0,
      currency: 'CNY',
      steps: [],
      remark: '',
      invoiceOID: '',
      display: 'none',
      columns:[
        {
          title: messages('mileage-subsidy-expense.key1'/*出发信息*/),
          dataIndex: 'start',
          width: '25%',
          render: (record, index) => {
            return <div>
              <div>{moment(index.departTime).format('YYYY-MM-DD HH:mm')}</div>
              <div>{record.place}</div>
            </div>
          }
        },
        {
          title: messages('mileage-subsidy-expense.key2'/*到达信息*/),
          dataIndex: 'end',
          width: '25%',
          render: (record, index) => {
            return <div>
              <div>{moment(index.arriveTime).format('YYYY-MM-DD HH:mm')}</div>
              <div style={{ overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>{record.place}</div>
            </div>
          }
        },
        {
          title: messages('mileage-subsidy-expense.key3'/*里程*/),
          dataIndex: 'mileage',
          width: '15%',
          render: (record, index) => {
            return <div>
              <div>{messages('mileage-subsidy-expense.key4'/*实际*/)}:{record.toFixed(2)}</div>
              <div>{messages('mileage-subsidy-expense.key5'/*参考*/)}:{index.referenceMileage.toFixed(2)}</div>
            </div>
          }
        },
        {
          title: messages('mileage-subsidy-expense.key6'/*事由说明*/),
          dataIndex: 'remark'
        }
      ],
      mileageExpenseList: menuRoute.getRouteItem('mileage-subsidy-expense','key'),
      visible: false
    }
  }


  componentWillMount() {
    const { params, company } = this.props;
    this.setState({
      order: params.order,
      type: params.type,
      pageLoading: true,
      invoiceOID: params.invoiceOID,
      currencyList:[{ currency: company.baseCurrency, currencyName: company.baseCurrency }]
    },() => {
      this.getCost(params.order.split(','));
      this.getOrders(params.order.split(','));
      this.state.type === 'edit-cost' && this.getFeeDetail();
    });
  }

  //编辑费用里程补贴详情
  getFeeDetail = () => {
    const { invoiceOID } = this.state;
    mileageExpenseService.getFeeDetail(invoiceOID).then(res => {});
  };

  onCancel = () => {
    this.setState({ visible:false })
  };

  goBack = () => {
    this.context.router.push(this.state.mileageExpenseList.url)
  };

  //根据profile来校验补贴金额
  controlPrice (amount) {
    const { totalSubsidy } = this.state;
    const { profile } = this.props;
    return new Promise((resolve,reject) =>{
      if(!profile['All.FeeAllowance.equal'] || profile['All.FeeAllowance.equal'] === 1){
        if(parseFloat(amount) <= parseFloat(totalSubsidy)){
          return resolve(true)
        }else{
          message.error(messages('mileage-subsidy-expense.key49')/*金额只能小于等于补贴总额*/);
          return reject(false)
        }
      }else if(profile['All.FeeAllowance.equal'] === 2){
        if(parseFloat(amount) === parseFloat(totalSubsidy)){
          return resolve(true)
        }else{
          message.error(messages('mileage-subsidy-expense.key50')/*金额只能等于补贴总额*/);
          return reject(false)
        }
      }else{
        return resolve(true)
      }
    })
  }

  //新建编辑费用
  handleNew = (e)=>{
    e.preventDefault();
    const { type, date } = this.state;
    this.props.form.validateFieldsAndScroll((err, values) => {
      if(!err) {
        this.controlPrice(values.amount).then(() => {
          values.currency = values.currencyCode;
          values.createdTime = moment(values.date).format('YYYY-MM-DD');
          values.amount = values.amount.toString();
          this.deleteObjectAttribute(
            values,
            ['totalMileage', 'referenceMileage', 'totalSubsidy', 'amountInfo', 'mileageDetail', 'currencyCode', 'type']
          );
          if(type === 'new-cost') {
            this.newCost(values)
          }
        })
      }
    })
  };

  //新建费用
  newCost(values) {
    this.setState({ pageLoading: true });
    const { order } = this.state;
    mileageExpenseService.generateCost(Object.assign(values, { orderIds: order.split(',') }))
      .then(response => {
        if (response.status === 200) {
          message.success(`${messages('common.save.success', { name: '' })}`);
          this.props.form.resetFields();
          this.goBack();
        }
      })
      .catch(e => {
        errorMessage(e.response);
      })
      .finally(()=> {
        this.setState({ loading: false, pageLoading: false });
      });
  }

  //删除对象属性
  deleteObjectAttribute(obj, values) {
    values.map(item => {
      delete obj[item]
    })
  }

  getTwoDecimal = num => {
    return (Math.round(num * 100) / 100)
  };

  //获取订单
  getOrders(orderIds) {
    this.setState({ tableLoading: true });
    mileageExpenseService.getOrders({ orderIds })
      .then(response => {
        this.setState({
          tableLoading: false,
          data: response.data.orders
        });
      });
  }

  //获取费用
  getCost(orderIds){
    mileageExpenseService.getMileageDetails({ orderIds }).then(res => {
      this.setState({
        pageLoading: false,
        totalSubsidy: res.data.totalPrice ? Number(res.data.totalPrice.toFixed(queryCurrencyPrecision(res.data.currency))) : Number(currencyPrecisionCal(res.data.currency, 0)),
        totalMileage: res.data.totalMileage || 0,
        referenceMileage: res.data.totalReferenceMileage || 0,
        currency: res.data.currency || 'CNY',
        steps: res.data.totalSteps.filter((step) => (step.amount > 0)),
      })
    })
  }

  handleRowClick = record => {
    this.setState({ record: record, visible: true })
  };

  renderMode = (value) => {
    if (value === 1001) {
      return messages('mileage-subsidy-expense.key55')/*手工创建*/;
    }
    if (value === 1002) {
      return messages('mileage-subsidy-expense.key56')/*定位创建*/;
    }
    return '-';
  };

  renderExpanded = (record) => {
    return record['viaPoints'] && record['viaPoints'][0]
      ? (
        <section className="mileage-point">
          {
            record['viaPoints'].map(value =>
              <Row className="mileage-point-row">
                <Col span={4}>
                  {moment(value.arrivalTime).format('YYYY-MM-DD HH:mm:ss')}
                </Col>
                <Col span={10}>
                  {value.place}
                </Col>
                <If value={value.originPoint}>
                  <Col span={10} className="mileage-detail-point_origin">
                    {messages('mileage-subsidy-expense.key59')/*[原定位]*/} {value.originPoint && JSON.parse(value.originPoint).place}
                  </Col>
                </If>
              </Row>
            )}
        </section>
      )
      : null;
  };

  render() {
    const { currencyList,columns, tableLoading, pageLoading, data, visible, record, date, totalSubsidy, totalMileage,
      referenceMileage, currency, type, remark, steps, priceList, display } = this.state;
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 16 }
    };
    let currencyPrecision = queryCurrencyPrecision(currency);
    return (
      <div className='new-mileage-cost'>
          <Spin spinning={pageLoading}>
              <h3 className='bottom-line'>{type === 'new-cost' ? messages('mileage-subsidy-expense.key33'/*新建费用*/) : messages('mileage-subsidy-expense.key34'/*编辑费用*/)}</h3>
              <Form style={{marginBottom:'60px'}} onSubmit={type === 'new-cost' ? this.handleNew : this.handleEdit}>
                <FormItem {...formItemLayout} label={messages('mileage-subsidy-expense.key7'/*类型*/)}>
                  {getFieldDecorator('type',)(
                    <span>{messages('mileage-subsidy-expense.key35'/*里程补贴*/)}</span>
                  )}
                </FormItem>
                <FormItem {...formItemLayout} label={messages('mileage-subsidy-expense.key36'/*日期*/)}>
                  {getFieldDecorator('date', {
                    rules: [{
                      required: true,
                      message: messages('mileage-subsidy-expense.key37'/*请选择月份*/)
                    }],
                    initialValue: moment(new Date())
                  })(
                    <DatePicker format='YYYY-MM-DD' />
                  )}
                </FormItem>
                <FormItem {...formItemLayout} label={messages('mileage-subsidy-expense.key8'/*金额*/)}>
                  {getFieldDecorator('amountInfo',)(
                    <Row>
                      <Col span={10}>
                        <FormItem>
                          {getFieldDecorator('currencyCode', {
                            rules: [{
                              required: true,
                              message: messages('mileage-subsidy-expense.key9'/*请选择币种*/)
                            }],
                            initialValue: currency ? currency : ''
                          })(
                            <Select optionLabelProp='value' disabled dropdownMatchSelectWidth={false}
                                    placeholder={messages('common.please.select')/* 请选择 */}>
                              {currencyList.map(item => <Option key={item.currency}>{item.currencyName}</Option>)}
                            </Select>
                          )}
                        </FormItem>
                      </Col>
                      <Col span={1}/>
                      <Col span={13}>
                        <FormItem>
                          {getFieldDecorator('amount',
                            {
                              rules:[{
                                required: true,
                                message: messages('mileage-subsidy-expense.key10'/*请输入合法的金额(小数点最多两位)*/)
                              }],
                              initialValue: totalSubsidy ? Number(totalSubsidy.toFixed(currencyPrecision)) : ''
                            })(
                            <InputNumber style={{width: '100%'}}
                                         precision={currencyPrecision}
                                         min={0}
                                         step={currencyPrecision ? 1 / Math.pow(10, currencyPrecision) : 1} />
                          )}
                        </FormItem>
                      </Col>
                    </Row>
                  )}
                </FormItem>
                  <FormItem {...formItemLayout} label={messages('mileage-subsidy-expense.key11'/*累计里程*/)}>
                    <Row>
                      <Col span={10}>
                        <FormItem>
                          {getFieldDecorator('totalMileage',{
                            initialValue: this.getTwoDecimal(totalMileage)
                          })(
                            <span>{this.getTwoDecimal(totalMileage).toFixed(2)}</span>
                          )}
                        </FormItem>
                      </Col>
                      <Col span={1}/>
                      <Col span={13}>
                        <FormItem {...formItemLayout} label={messages('mileage-subsidy-expense.key12'/*参考里程(KM)*/)}>
                          {getFieldDecorator('referenceMileage',{
                            initialValue:this.getTwoDecimal(referenceMileage)
                          })(
                            <span>{this.getTwoDecimal(referenceMileage).toFixed(2)}</span>
                          )}
                        </FormItem>
                      </Col>
                    </Row>
                  </FormItem>
                  <FormItem {...formItemLayout} label={messages('mileage-subsidy-expense.key13'/*补贴总额*/)}>
                    {getFieldDecorator('totalSubsidy',{
                      initialValue: common.formatCurrency(totalSubsidy)
                    })(
                      <span>{currency}&nbsp;{totalSubsidy.toFixed(currencyPrecision)}</span>
                    )}
                  </FormItem>
                <Row style={{marginBottom:'20px'}}>
                  <Col span={6} style={{textAlign:'right'}}>
                    <span className="valuation-detail">
                       <Popover placement="top"
                                overlayStyle={{ width: 400 }}
                                content={
                                  <Table
                                    columns={[{
                                      title: messages('mileage-subsidy-expense.key15'/*里程数*/), dataIndex: 'startUnit',
                                      render: (startUnit, record) => `${startUnit.toFixed(2)}${record.endUnit === -1 ? '以上' : ('~' + record.endUnit.toFixed(2))}`
                                    } , {
                                      title: messages('mileage-subsidy-expense.key16'/*单价/KM*/)+` ${currency}`, dataIndex: 'unitPrice',
                                      render:value => this.filterMoney(value, currencyPrecision)
                                    } , {
                                      title: messages('mileage-subsidy-expense.key8'/*金额*/), dataIndex: 'amount',
                                      render:value => this.filterMoney(value, currencyPrecision)
                                    }]}
                                    dataSource={steps}
                                    rowKey="startUnit"
                                    pagination={false}
                                    size="small"/>}>
                         <a style={{ marginLeft: 10 }}>{messages('mileage-subsidy-expense.key14'/*查看计价明细*/)}</a>
                       </Popover>
                    </span>
                  </Col>
                </Row>
                  <FormItem {...formItemLayout} label={messages('mileage-subsidy-expense.key17'/*里程明细*/)}>
                    {getFieldDecorator('mileageDetail')(
                      <Table
                        rowKey='id'
                        columns={columns}
                        dataSource={data}
                        bordered
                        size="middle"
                        loading={tableLoading}
                        onRow={record => ({ onClick: () => this.handleRowClick(record) })}
                        expandedRowRender={this.renderExpanded}
                        rowClassName={record => (record.viaPoints || []).length > 0 ? '' : 'row-expand-display-none'}/>
                    )}
                  </FormItem>
                  <FormItem {...formItemLayout}  label={messages('mileage-subsidy-expense.key6'/*事由说明*/)}>
                    {getFieldDecorator('remark',{
                      initialValue:remark
                    })(
                      <TextArea autosize={{minRows: 4}}
                                style={{minWidth:'100%'}}
                                placeholder={messages('mileage-subsidy-expense.key18'/*请输入，最多输入200个汉字*/)}
                                maxLength="200"/>
                    )}
                  </FormItem>
                  <Affix offsetBottom={0} className="bottom-bar">
                    <Button onClick={this.goBack}>{messages('common.back')}</Button>
                    <Button type="primary" htmlType="submit" disabled={type === 'edit-cost'}>{messages('common.save')}</Button>
                  </Affix>
              </Form>
            <Modal
              visible={visible}
              title={messages('mileage-subsidy-expense.key17'/*里程明细*/)}
              footer={[]}
              onCancel={this.onCancel}
              className="mileage-detail-modal">
              <Row>
                <Col span={4}>{messages('mileage-subsidy-expense.key51')/*创建方式*/}：</Col>
                <Col span={20}>{this.renderMode(record && record.createdMode)}</Col>
              </Row>
              <Row>
                <Col span={4}>{messages('mileage-subsidy-expense.key19'/*上车时间*/)}:</Col>
                <Col span={20}>{record && moment(record.departTime).format('YYYY-MM-DD HH:mm')}</Col>
              </Row>
              <Row>
                <Col span={4}>{messages('mileage-subsidy-expense.key20'/*上车地点*/)}:</Col>
                <Col span={20}>{record && record.start.place}</Col>
              </Row>

              <If value={record && record.viaPoints && record.viaPoints[0]}>
                <Row>
                  <Col span={4}>{messages('mileage-subsidy-expense.key68')/*途径信息*/}</Col>
                  <Col span={20}>
                    {record && record.viaPoints && record.viaPoints.map(value => {
                      return (
                        <section className="mileage-detail-point">
                          <div>
                            {moment(value.arrivalTime).format('YYYY-MM-DD HH:mm')}
                          </div>
                          <div>
                            {value.place}
                          </div>
                          <If value={value.originPoint}>
                            <div className="mileage-detail-point_origin">
                              {messages('mileage-subsidy-expense.key59')/*[原定位]*/}{value.originPoint && JSON.parse(value.originPoint).place}
                            </div>
                          </If>
                        </section>
                      );
                    })}
                  </Col>
                </Row>
              </If>
              <Row>
                <Col span={4}>{messages('mileage-subsidy-expense.key21'/*下车时间*/)}:</Col>
                <Col span={20}>{record && moment(record.arriveTime).format('YYYY-MM-DD HH:mm')}</Col>
              </Row>
              <Row>
                <Col span={4}>{messages('mileage-subsidy-expense.key22'/*下车地点*/)}:</Col>
                <Col span={20}>{record && record.end.place}</Col>
              </Row>
              <Row>
                <Col span={6}>{messages('mileage-subsidy-expense.key23'/*实际里程(KM)*/)}:</Col>
                <Col span={18}>{record && record.mileage.toFixed(2)}</Col>
              </Row>
              <Row>
                <Col span={6}>{messages('mileage-subsidy-expense.key12'/*参考里程(KM)*/)}:</Col>
                <Col span={18}>{record && record.referenceMileage.toFixed(2)}</Col>
              </Row>
              <Row>
                <Col span={4}>{messages('mileage-subsidy-expense.key6'/*事由说明*/)}:</Col>
                <Col span={20}>{record && record.remark || '-'}</Col>
              </Row>
            </Modal>
          </Spin>
      </div>
    )
  }
}

NewMileageCost.contextTypes = {
  router:React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    profile: state.login.profile,
    company: state.login.company
  }
}

const wrappedNewMileageCost = Form.create()(NewMileageCost);
export default connect(mapStateToProps)(wrappedNewMileageCost)
